<?php

/**
 * @category   MM
 * @package    MM_Service
 */
class MM_Service_Admin_EventFiles extends Mediad2_Service_Abstract
{
	/**
	 * 初始化
	 */
	public function init()
	{
		$this->setMapper('MM_Mapper_EventFiles');
		$this->setModel('MM_Model_EventFiles');
	}
	
	/**
	 * upload event files
	 * @param int $eid
	 * @param int $esid
	 * @param int $uid
	 * @param string $desc
	 * @param string $upload_name
	 * @return Mediad2_Model_Result
	 */
	public function uploadEventFiles($eid, $esid, $uid, $desc=null, $upload_name='Filedata')
	{
		try {
			$sourcetype = Mediad2_Model_Files::SOURCETYPE_PHONE;
			$sourceid 	= $uid;
	
			//上传文件接收和处理
			$serviceFiles = new Mediad2_Service_Admin_Files();
			$result = $serviceFiles->upload($sourcetype, $sourceid, $upload_name);
	
			//处理文件出现失败，则终止处理
			if ($result->getCode() == $result::CODE_FAILURE) {
				return $result;
			}
	
			//处理上传文件正常，则继续
			//获取fid
			$files = $result->getData();
	
			//保存event_files记录
			$eventFiles = new MM_Model_EventFiles();
			$eventFiles->setFid($files->getFid());
			$eventFiles->setEid($eid);
			$eventFiles->setEsid($esid);
			$eventFiles->setUid($uid);
			$eventFiles->setFilename($files->getFilename());
			$eventFiles->setFiletype($files->getFiletype());
			$eventFiles->setFileimg($files->getFileimg());
			$eventFiles->setFilesize($files->getFilesize());
			$eventFiles->setFilepath($files->getFilepath());
			$eventFiles->setFiledesc($desc);
			$eventFiles->setSourcetype($files->getSourcetype());
			$eventFiles->setAddtime($files->getAddtime());
			$eventFiles->setLastime($files->getAddtime());
			$eventFiles->setStatus($files->getStatus());
			$eventFiles->setImgdate($files->getImgdate());
			$eventFiles->setImginfo($files->getImginfo());
			$eventFiles->setPosition($files->getPosition());
			$eventFiles->setSharevalue(0);
			$eventFiles->setFavcount(0);
			$eventFiles->setCommentcount(0);
	
			//插入到数据库
			$this->getMapper()->insert($eventFiles->toArray());
	
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
	
		} catch (Zend_Exception $e) {
			$this->handleException($e);
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'upload event file error'.$e->getMessage());
		}
	}
	
	/**
	 * get event files list
	 * @param int $eid
	 * @param int $esid
	 * @param int $uid
	 * @param string $do
	 * @param int $addtime
	 * @return Mediad2_Model_Result
	 */
	public function getEventFiles($eid, $esid, $uid, $do, $addtime)
	{
		try {
			//var
			$data = array();
			$serviceEvent = new MM_Service_Admin_Event();
			
			//判断是否已关注活动
			if (!$serviceEvent->isFollowedEvent($eid, $uid)) {	
				return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,'未关注活动',$data);
			}
	
			//封装where
			$where = sprintf("status = %s and eid = %s", Mediad2_Model_Files::STATUS_NORMAL, $eid);
			if (!empty($esid)) $where .= " and esid = $esid";
			switch ($do) {
				case "first":
					if (!empty($addtime)) $where .= " and addtime > $addtime";
					break;
				case "more":
				default:
					if (!empty($addtime)) { 
						$where .= " and addtime < $addtime";
					} else {
						return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'当获取更多图片时，时间不能为空');
					}
					break;
			}
	
			$order = "fid desc";
	
			$fields = array(
					'fid','eid','esid', 'uid',
					'filename','filetype','fileimg','filepath','filedesc',
					'addtime','imgdate','sharevalue','favcount','commentcount'
			);
			$pageindex = 1;
			$pagenum = 30;
	
			$mapper = $this->getMapper();
			$arrFiles = $mapper->fetchAll($pageindex, $pagenum, $where, $order, $fields);
	
			if (count($arrFiles)>0) {
				foreach ($arrFiles as $key => $file) {
					$arrFid[] = $file['fid'];
					$arrFiles[$key]['isfav'] = 0;
					$arrFiles[$key]['iscomment'] = 0;
				}
				$strFid = implode(',', $arrFid);
				$objecttype = 'event_files';
				$whereFav = "eid = $eid AND objectid in ( $strFid ) AND objecttype='$objecttype'";
				$whereComment = "isdel = 0 AND eid = $eid AND objectid in ( $strFid ) AND objecttype='$objecttype'";
				$order = " addtime desc ";
				$fields = array('objectid','uid');
				//获取数据
				$serviceUserFav = new MM_Service_Admin_EventUserFavorite();
				$arrFav = $serviceUserFav->getMapper()->fetchAll(null,null,$whereFav,$order,$fields);
				$serviceUserComment = new MM_Service_Admin_EventUserComment();
				$arrComment = $serviceUserComment->getMapper()->fetchAll(null,null,$whereComment,$order,$fields);
				//对fav数据进行处理
				$arrFileFav = array();
				foreach ($arrFav as $key => $fav) {
					if (!array_key_exists($fav['objectid'], $arrFileFav)) {
						$arrFileFav[$fav['objectid']][0] = $fav['uid'];
					} else {
						$arrFileFav[$fav['objectid']][] = $fav['uid'];
					}
				}
				//对comment数据进行处理
				$arrFileComment = array();
				foreach ($arrComment as $key => $comment) {
					if (!array_key_exists($comment['objectid'], $arrFileComment)) {
						$arrFileComment[$comment['objectid']][0] = $comment['uid'];
					} else {
						if (!in_array($comment['uid'], $arrFileComment[$comment['fid']])) {
							$arrFileComment[$comment['objectid']][] = $comment['uid'];
						}
					}
				}
	
				foreach ($arrFiles as $key => $file) {
					if (count($arrFileFav)>0) {
						if (in_array($uid, $arrFileFav[$file['fid']])) $arrFiles[$key]['isfav'] = 1;
					}
					if (count($arrFileComment)>0) {
						if (in_array($uid, $arrFileComment[$file['fid']])) $arrFiles[$key]['iscomment'] = 1;
					}
				}
			}
	
			$data['files'] = $arrFiles;
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$data);
	
		} catch (Zend_Exception $e) {
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * get file info
	 * @param int $eid
	 * @param int $fid
	 * @return Mediad2_Model_Result
	 */
	public function getFilesInfo($eid, $fid)
	{
		try {
			$where = "fid = $fid AND eid = $eid";
			$fields = array(
					'fid','eid','esid','uid',
					'filename','filetype','fileimg','filepath','filedesc',
					'addtime','imgdate','sharevalue','favcount','commentcount'
			);
			$order = "fid asc";
			return $this->getFieldsBy($where,$fields,$order);
	
		} catch (Zend_Exception $e) {
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	
	/**
	 * update file desc
	 * @param int $fid
	 * @param int $uid
	 * @param string $filedesc
	 * @return Mediad2_Model_Result
	 */
	public function updateFilesDesc($fid,$uid,$filedesc)
	{
		try {
			$filedesc = substr($filedesc, 0, 254);
			//更新files表
			$where = "fid = $fid AND uid = $uid";
			$row = array(
					'filedesc' => $filedesc,
			);
			$row = $this->getMapper()->__updateSQL($row, $where);
			if ($row>0) {
				//返回结果--成功
				return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
			}else{
				return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'操作不成功，只能对自己上传的照片增加描述哦');
			}
	
		} catch (Zend_Exception $e) {
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * delete file
	 * @param int $fid
	 * @param int $uid
	 * @return Mediad2_Model_Result
	 */
	public function deleteFiles($fid,$uid)
	{
		try {
			//更新files表
			$where = "fid = $fid AND uid = $uid";
			$row = array(
					'status' => MM_Model_EventFiles::STATUS_DELETED,
			);
			$row = $this->getMapper()->__updateSQL($row, $where);
			if ($row>0) {
				//返回结果--成功
				return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
			}else{
				return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'操作不成功，只能删除自己上传的照片哦');
			}
	
		} catch (Zend_Exception $e) {
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * get file comment
	 * @param int $fid
	 * @param int $addtime
	 * @return Mediad2_Model_Result
	 */
	public function getFilesComment($fid, $addtime)
	{
		try {
			$where = "objecttype = 'event_files'  AND objectid = $fid ";
			if (!empty($addtime)) $where .= " and addtime < $addtime";
			$order = "eucid desc";
			$pageindex = 1;
			$pagenum = 30;
			$serviceUserComment = new MM_Service_Admin_EventUserComment();
			return $serviceUserComment->fetchAll($pageindex,$pagenum,$where,$order,true);
	
		} catch (Zend_Exception $e) {
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * get file fav
	 * @param int $fid
	 * @param int $addtime
	 * @return Mediad2_Model_Result
	 */
	public function getFilesFav($fid, $addtime)
	{
		try {
			$where = "objecttype = 'event_files'  AND objectid = $fid ";
			if (!empty($addtime)) $where .= " and addtime < $addtime";
			$order = "eufid desc";
			$pageindex = 1;
			$pagenum = 30;
			$serviceUserFav = new MM_Service_Admin_EventUserFavorite();
			return $serviceUserFav->fetchAll($pageindex,$pagenum,$where,$order,true);
	
		} catch (Zend_Exception $e) {
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * 喜欢/取消喜欢
	 * @param int $eid
	 * @param int $fid
	 * @param int $uid
	 * @param string $action
	 * @return Mediad2_Model_Result
	 */
	public function favorFiles($eid, $fid, $uid, $action)
	{
		//var
		$serviceFav = new MM_Service_Admin_EventUserFavorite();
		$objecttype = 'event_files';
		$objectid = $fid;
		
		//事务处理
		$db1 = Zend_Registry::get('db1');
		$db1->beginTransaction();
	
		try {
			if ($action == 'cancel') {	//取消喜欢
	
				if (!$serviceFav->isFavored($eid, $uid, $objecttype, $objectid)) {
					return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
				} else {
					//删除event_user_favorite表记录
					$where = "eid = $eid AND uid = $uid AND objectid = $objectid AND objecttype = '$objecttype'";
					$serviceFav->getMapper()->deleteBy($where);
	
					//更新files表，设置favcount-1
					$where = "fid = $fid";
					$row = array(
							'favcount' => new Zend_Db_Expr("favcount - 1"),
					);
					$this->getMapper()->__updateSQL($row, $where);
				}
	
			} else { 	//喜欢
	
				if ($serviceFav->isFavored($eid, $uid, $objecttype, $objectid)) {
					return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
				} else {
					//新增fav表记录
					$model = new MM_Model_EventUserFavorite();
					$model->setEid($eid);
					$model->setUid($uid);
					$model->setAddtime(time());
					$model->setObjecttype($objecttype);
					$model->setObjectid($objectid);
					
					$serviceFav->getMapper()->insert($model->toArray());
	
					//更新files表，设置favcount+1
					$where = "fid = $fid";
					$row = array(
							'favcount' => new Zend_Db_Expr("favcount + 1"),
					);
					$this->getMapper()->__updateSQL($row, $where);
				}
			}
	
			//提交事务
			$db1->commit();
	
			//返回结果--成功
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
	
		} catch (Zend_Exception $e) {
	
			//回滚事务
			$db1->rollback();
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * get user files
	 * @param int $uid
	 * @param int $addtime
	 * @param int $needgroup
	 * @return Mediad2_Model_Result
	 */
	public function getUserFiles($uid, $addtime, $needgroup=0)
	{
		try {
			$where = sprintf("status = %s and uid = %s", Mediad2_Model_Files::STATUS_NORMAL, $uid);
			if (!empty($addtime)) $where .= " and addtime < $addtime";
			$order = "fid desc";
			$pageindex = 1;
			$pagenum = 30;
			$result = $this->fetchAll($pageindex,$pagenum,$where,$order,true);
			if ($result->getCode()==$result::CODE_FAILURE) {
				return $result;
			}
			$arrFiles = $result->getData();
			if ($needgroup) {
				$arrFiles = $this->_sortFilesBydate($arrFiles);
			}
			
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$arrFiles);
		
		} catch (Zend_Exception $e) {
		
			//出错处理
			$this->handleException($e);
		
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	//------------------------------------------
	// 私有方法
	//------------------------------------------
	
	/**
	 * 根据日期，对文件进行排序
	 *
	 * @param array $arrFiles
	 * @return array
	 */
	private function _sortFilesBydate($arrFiles)
	{
		$data = array();
		foreach ($arrFiles as $key => $file) {
			$k = date('Y年m月d日',$file['addtime']);
			$data[$k][] = $file;
		}
		krsort($data);
		return $data;
	}
	
}